import 'package:flutter/material.dart';
import 'package:get/get.dart' hide SnackPosition;
import 'package:image_picker/image_picker.dart';
import 'package:uuid/uuid.dart';
import '../../common/index.dart';

class AddPlantController extends GetxController {
  AddPlantController();

  // 植物名称输入控制器
  late TextEditingController name_controller;

  // 选择的图片文件
  Rx<XFile?> selected_image = Rx<XFile?>(null);

  // 加载状态
  RxBool is_loading = false.obs;

  // 动画控制变量
  final RxDouble back_button_scale = 1.0.obs;
  final RxDouble plant_icon_scale = 1.0.obs;
  final RxDouble save_button_scale = 1.0.obs;
  final RxBool is_focused = false.obs;
  final RxDouble rotation_value = 0.0.obs;
  final RxBool name_error_shake_controller = false.obs;

  // 设置按钮缩放
  void set_back_button_scale(double scale) {
    back_button_scale.value = scale;
  }

  void set_plant_icon_scale(double scale) {
    plant_icon_scale.value = scale;
  }

  void set_save_button_scale(double scale) {
    save_button_scale.value = scale;
  }

  // 设置输入框焦点状态
  void set_is_focused(bool focused) {
    is_focused.value = focused;
  }

  // 触发名称错误抖动动画
  void trigger_name_error_shake() {
    name_error_shake_controller.value = true;
  }

  // 开始图标旋转动画
  void start_rotation_animation() {
    rotation_value.value += 0.25;
    update();
  }

  _initData() {
    // 启动定时旋转动画
    Future.delayed(Duration(milliseconds: 500), () {
      if (selected_image.value == null) {
        start_rotation_animation();
      }
    });
    update(["add_plant"]);
  }

  void onTap() {}

  // 从相册上传图片
  Future<void> pick_image() async {
    try {
      is_loading.value = true;
      update(["add_plant"]);

      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);

      if (image != null) {
        selected_image.value = image;
      }
    } finally {
      is_loading.value = false;
      update(["add_plant"]);
    }
  }

  void on_save_tap() async {
    // 验证并保存植物数据
    if (name_controller.text.isEmpty) {
      trigger_name_error_shake();
      SmartDialogHelper.show_snackbar(
        title: 'Error',
        message: 'Please enter a plant name',
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
      return;
    }

    if (selected_image.value == null) {
      set_plant_icon_scale(0.9);
      Future.delayed(Duration(milliseconds: 100), () {
        set_plant_icon_scale(1.0);
      });
      SmartDialogHelper.show_snackbar(
        title: 'Error',
        message: 'Please select an image',
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
      return;
    }

    // 永久保存图片
    final image_path = await ImageStorageService().save_image(
      selected_image.value!,
    );
    if (image_path.isEmpty) {
      SmartDialogHelper.show_snackbar(
        title: 'Error',
        message: 'Failed to save image',
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
      return;
    }

    // 创建植物对象
    final plant = Plant(
      id: Uuid().v4(),
      image: image_path,
      image_list: {},
      name: name_controller.text,
      water_day: '7', // 默认浇水间隔
      create_time: DateTime.now().toIso8601String(),
    );

    // 保存植物
    await PlantService().add_plant(plant);

    // 返回植物页面并刷新数据
    RouteUtil.pop(true);
  }

  // 水仙花数的计算
  int calculate_narcissistic_number(int n) {
    int sum = 0;
    int temp = n;
    while (temp > 0) {
      int digit = temp % 10;
      sum += digit * digit * digit;
      temp ~/= 10;
    }
    return sum;
  }

  @override
  void onInit() {
    super.onInit();
    name_controller = TextEditingController();
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  @override
  void onClose() {
    super.onClose();
    name_controller.dispose();
  }
}
